//
//  CommentListVC.m
//  WanCaiC8
//
//  Created by tangang on 2018/4/23.
//  Copyright © 2018年 tangang. All rights reserved.
//

#import "CommentListVC.h"
#import "CommentsCell.h"
#import "CommentVM.h"
#import "CommentsTextView.h"
#import "CommentModel.h"
#import "SocketRocketUtility.h"
#import "CommentDetailVC.h"
#import "MJRefresh.h"
#import "OtherInfoVC.h"
#import "PlanVM.h"
@interface CommentListVC ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (nonatomic ,strong) UITableView   *tableView;
@property (nonatomic ,strong) NSMutableArray    *goodComments;
@property (nonatomic ,strong) NSMutableArray    *comments;
@property (nonatomic ,strong) CommentsTextView *cTextView;
@property (nonatomic ,strong) NSMutableArray  *commentsImages;
@end

@implementation CommentListVC{
    RITLPhotoNavigationViewModel * viewModel;
    CommentModel    *selectModel;

    NSString        *sendStr;
    NSString        *lastId;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"评论";
    viewModel = [RITLPhotoNavigationViewModel new];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)setID:(NSString *)ID{
    _ID=ID;
    [self getWonderfulComment];
}

- (void)setLType:(NSString *)lType{
    _lType=lType;
    [self getWonderfulComment];
}

#pragma mark -- 获取精彩评论
- (void)getWonderfulComment{
    WS(weakSelf);
    if (self.type==CommentListTypePlan) {
        [[PlanVM manage] getWonderfulCommentId:self.lType andType:1 andCount:3 andUserId:self.userId Success:^(id returnValue) {
            weakSelf.goodComments=returnValue;
            [weakSelf.tableView reloadData];
            lastId=@"0";
            [weakSelf getComments];
        } andFail:^(NSString *errorMessage, NSError *error) {
            [weakSelf.tableView.header endRefreshing];
        }];;
    }else{
        [[CommentVM manage] getWonderfulCommentId:self.ID andType:2 andCount:3 Success:^(id returnValue) {
            weakSelf.goodComments=returnValue;
            [weakSelf.tableView reloadData];
            lastId=@"0";
            [weakSelf getComments];
        } andFail:^(NSString *errorMessage, NSError *error) {
            [weakSelf.tableView.header endRefreshing];
        }];
    }
    
    
    
}

#pragma mark -- 获取评论
- (void)getComments{
    WS(weakSelf);
    
    if (self.type==CommentListTypePlan) {
        [[PlanVM manage] getCommentListWithId:self.lType andType:1 andLast:lastId andPageSize:20 andUserId:self.userId Success:^(id returnValue) {
            NSArray *arr=returnValue;
            if (arr.count<[defaultPageSize integerValue]) {
                [weakSelf.tableView.footer noticeNoMoreData];
            }else{
                [weakSelf.tableView.footer endRefreshing];
            }
            [weakSelf.comments addObjectsFromArray:returnValue];
            [weakSelf.tableView reloadData];
            [weakSelf.tableView.header endRefreshing];
        } andFail:^(NSString *errorMessage, NSError *error) {
            [weakSelf.tableView.header endRefreshing];
            [weakSelf.tableView.footer endRefreshing];
        }];
    }else{
        [[CommentVM manage] getCommentListWithId:self.ID andType:2 andLast:lastId andPageSize:20 Success:^(id returnValue) {
            NSArray *arr=returnValue;
            if (arr.count<[defaultPageSize integerValue]) {
                [weakSelf.tableView.footer noticeNoMoreData];
            }else{
                [weakSelf.tableView.footer endRefreshing];
            }
            [weakSelf.comments addObjectsFromArray:returnValue];
            [weakSelf.tableView reloadData];
            [weakSelf.tableView.header endRefreshing];
        } andFail:^(NSString *errorMessage, NSError *error) {
            [weakSelf.tableView.header endRefreshing];
            [weakSelf.tableView.footer endRefreshing];
        }];
    }
    
    
}

#pragma mark -- 发布评论
- (void)publishComment{
    WS(weakSelf);
    [SVProgressHUD show];
    [self postImageWithDoneArr:[NSMutableArray new] done:^(NSMutableArray *arr) {
        if (weakSelf.type==CommentListTypePlan) {
            [[PlanVM manage] publishWithId:self.lType andType:1 andContent:[[SocketRocketUtility instance] sendMessageConversion:self.cTextView.textView.text] andCommentType:1 andUserId:self.userId andPic:arr Success:^(id returnValue) {
                [self.commentsImages removeAllObjects];
                sendStr=nil;
                [weakSelf addRepaly];
                [weakSelf.cTextView removeSelf];
                [SVProgressHUD dismiss];
            } andFail:^(NSString *errorMessage, NSError *error) {
                
            }];
        }else{
            [[CommentVM manage] publishWithId:selectModel.Id andType:2 andContent:[[SocketRocketUtility instance] sendMessageConversion:self.cTextView.textView.text] andCommentType:2 andPic:arr Success:^(id returnValue) {
                [self.commentsImages removeAllObjects];
                sendStr=nil;
                [weakSelf addRepaly];
                [weakSelf.cTextView removeSelf];
                [SVProgressHUD dismiss];
            } andFail:^(NSString *errorMessage, NSError *error) {
                
            }];
        }
        
    }];
    
    
    
}

- (void)addRepaly{
    for (CommentModel *cModel in self.goodComments) {
        if ([cModel.Id isEqualToString:selectModel.Id]) {
            cModel.ReplayCount+=1;
        }
    }
    for (CommentModel *cModel in _comments) {
        if ([cModel.Id isEqualToString:selectModel.Id]) {
            cModel.ReplayCount+=1;
        }
    }
    [self.tableView reloadData];
}



- (void)postImageWithDoneArr:(NSMutableArray *)doneArr done:(void(^)(NSMutableArray *arr))doneBlock{
    if (doneArr.count==self.commentsImages.count) {
        doneBlock(doneArr);
        return;
    }
    WS(weakSelf);
    [[BaseVM manage] postImageWithImage:self.commentsImages[doneArr.count] andType:3 andSuccess:^(id returnValue) {
        [doneArr addObject:[returnValue objectForKey:@"ResouceId"]];
        [weakSelf postImageWithDoneArr:doneArr done:doneBlock];
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

#pragma mark -- 对评论进行回复
- (void)replayComment:(CommentModel *)model{
    selectModel=model;
    [self.cTextView.textView becomeFirstResponder];
}
#pragma mark -- 对评论进行点赞
- (void)likeComment:(CommentModel *)model{
    self.tableView.userInteractionEnabled=NO;
    WS(weakSelf);
    [[CommentVM manage] clickLikeWithId:model.Id andType:2 andOperationType:model.IsLike?2:1 Success:^(id returnValue) {
        [weakSelf refreshPraise:model];
    } andFail:^(NSString *errorMessage, NSError *error) {
        weakSelf.tableView.userInteractionEnabled=YES;
    }];
}

#pragma mark -- 查看更多回复
- (void)lookMoreReplay:(CommentModel *)model{
    CommentDetailVC *vc=[[CommentDetailVC alloc] init];
    vc.type=self.type;
    vc.model=model;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)refreshPraise:(CommentModel *)model{
    model.IsLike=!model.IsLike;
    if (model.IsLike) {
        model.StarCount+=1;
    }else{
        model.StarCount-=1;
    }
    self.tableView.userInteractionEnabled=YES;
    [self.tableView reloadData];
}


#pragma mark -- 选择照片
- (void)selectPic{
    
    if (self.commentsImages.count>2) {
        [SVProgressHUD showErrorWithStatus:@"最多只能上传3张图片"];
        return;
    }
    
    sendStr=self.cTextView.textView.text;
    [self.cTextView removeSelf];
    UIAlertController *alertCtrl=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancleAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];;
    UIAlertAction *albumAction=[UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        WS(weakSelf);
        viewModel.RITLBridgeGetImageBlock = ^(NSArray  * images){
            for (NSDictionary *dict in images) {
                [weakSelf.commentsImages addObject:[dict objectForKey:@"image"]];
            }
            [weakSelf.cTextView.textView becomeFirstResponder];
        };
        self.hidesBottomBarWhenPushed = NO;
        viewModel.maxNumberOfSelectedPhoto=3-self.commentsImages.count;
        RITLPhotoNavigationViewController * viewController = [RITLPhotoNavigationViewController photosViewModelInstance:viewModel];
        [self presentViewController:viewController animated:true completion:^{}];
    }];
    UIAlertAction *cameraAction=[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        UIImagePickerController * ipc = [[UIImagePickerController alloc] init];
        ipc.delegate = self;
        ipc.sourceType = sourceType;
        [self presentViewController:ipc animated:YES completion:nil];
    }];
    [alertCtrl addAction:cancleAction];
    [alertCtrl addAction:albumAction];
    [alertCtrl addAction:cameraAction];
    [self presentViewController:alertCtrl animated:YES completion:nil];
}

#pragma mark - tableView输入框遮挡
- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    CGFloat keyboardTop = keyboardRect.origin.y;
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    [self.cTextView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@(keyboardTop+(SCREEN_WIDTH-60)/6+10+HEIGHT_CHATBOXVIEW-(self.cTextView.imageArr.count>0?(SCREEN_WIDTH-60)/6+5:0)));
    }];
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    NSDictionary* userInfo = [notification userInfo];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    [self.cTextView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@(SCREEN_HEIGHT+(self.cTextView.imageArr.count>0?(SCREEN_WIDTH-60)/6:0)));
    }];
    [UIView commitAnimations];
    
}

#pragma mark -- UINavigationControllerDelegate, UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (!self.commentsImages) {
        self.commentsImages=[[NSMutableArray alloc]init];
    }
    [self.commentsImages addObject:image];
    [self dismissViewControllerAnimated:YES completion:^{
        [self.cTextView.textView becomeFirstResponder];
    }];
    
    
}

#pragma mark -- UITableViewDelegate ,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return self.goodComments.count;
    }else if (section==1){
        return self.comments.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommentModel *model;
    if (indexPath.section==0) {
        model=self.goodComments[indexPath.row];
    }else{
        model=self.comments[indexPath.row];
    }
    WS(weakSelf);
    if (model.ReplayCount>0) {
        CommentsCell *cell=[tableView dequeueReusableCellWithIdentifier:@"CommentsCell" forIndexPath:indexPath];
        [cell setModel:model];
        cell.lookComment = ^(CommentModel *model) {
            [weakSelf lookMoreReplay:model];
        };
        cell.likeComment = ^(CommentModel *model) {
            [weakSelf likeComment:model];
        };
        cell.replayComment = ^(CommentModel *model) {
            [weakSelf replayComment:model];
        };
        cell.lookUser = ^(CommentModel *model) {
//            OtherInfoVC *vc=[[OtherInfoVC alloc]init];
//            vc.userId=model.ParentComment.UserId;
//            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        return cell;
    }
    CommentsCell *cell=[tableView dequeueReusableCellWithIdentifier:@"CommentsCell1" forIndexPath:indexPath];
    [cell setModel:model];
    cell.lookComment = ^(CommentModel *model) {
        [weakSelf lookMoreReplay:model];
    };
    cell.likeComment = ^(CommentModel *model) {
        [weakSelf likeComment:model];
    };
    cell.replayComment = ^(CommentModel *model) {
        [weakSelf replayComment:model];
    };
    cell.lookUser = ^(CommentModel *model) {
//        OtherInfoVC *vc=[[OtherInfoVC alloc]init];
//        vc.userId=model.ParentComment.UserId;
//        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0&&self.goodComments.count>0) {
        return 35;
    }else if (section==1&&self.comments.count>0){
        return 35;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section==0) {
        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 35)];
        QXLable *lab=[[QXLable alloc]initWithFount:15];
        lab.text=@"精彩评论";
        [lab setFrame:CGRectMake(10, 0, 200, 35)];
        [view addSubview:lab];
        return view;
    }else if (section==1){
        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
        view.backgroundColor=[UIColor whiteColor];
        QXLable *lab=[[QXLable alloc]initTitle];
        lab.text=@"最新评论";
        [lab setFrame:CGRectMake(10, 5, 200, 35)];
        [view addSubview:lab];
        
        UIView *line=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 5)];
        line.backgroundColor=DEFAULTBGCOLOR;
        [view addSubview:line];
        return view;
    }
    return nil;
}

#pragma mark -- 懒加载
- (UITableView *)tableView{
    if (!_tableView) {
        WS(weakSelf);
        _tableView=[[UITableView alloc]init];
        _tableView.dataSource=self;
        _tableView.delegate=self;
        _tableView.backgroundColor=DEFAULTBGCOLOR;
        [_tableView registerClass:[CommentsCell class] forCellReuseIdentifier:@"CommentsCell"];
        [_tableView registerClass:[CommentsCell class] forCellReuseIdentifier:@"CommentsCell1"];
        _tableView.estimatedRowHeight=400;
        _tableView.rowHeight=UITableViewAutomaticDimension;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        _tableView.header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf.goodComments removeAllObjects];
            [weakSelf.comments removeAllObjects];
            [weakSelf.tableView reloadData];
            [weakSelf getWonderfulComment];
        }];
        _tableView.footer=[MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            CommentModel *model=weakSelf.comments.lastObject;
            lastId=model.Id;
            [weakSelf getComments];
        }];
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
    }
    return _tableView;
}

- (NSMutableArray *)goodComments{
    if (!_goodComments) {
        _goodComments=[[NSMutableArray alloc]init];
    }
    return _goodComments;
}

- (NSMutableArray *)comments{
    if (!_comments) {
        _comments=[[NSMutableArray alloc]init];
    }
    return _comments;
}

- (CommentsTextView *)cTextView{
    if (!_cTextView) {
        WS(weakSelf);
        _cTextView=[[CommentsTextView alloc]init];
        _cTextView.textView.text=sendStr;
        [_cTextView setImageArr:self.commentsImages];
        _cTextView.clickEmj = ^(BOOL isFace) {
            if (isFace) {
                [weakSelf.cTextView.textView resignFirstResponder];
                [weakSelf.cTextView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(@(SCREEN_HEIGHT+(self.cTextView.imageArr.count>0?(SCREEN_WIDTH-60)/6:0)));
                }];
            }else{
                [weakSelf.cTextView.textView becomeFirstResponder];
            }
        };
        _cTextView.showPic = ^ {
            [weakSelf selectPic];
        };
        
        _cTextView.sendBlock = ^{
            [weakSelf publishComment];
            
        };
        _cTextView.removeBlock = ^{
            [weakSelf.cTextView removeFromSuperview];
            weakSelf.cTextView=nil;
        };
        [self.view addSubview:_cTextView];
        
        [_cTextView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(self.view);
            make.height.mas_equalTo(@0);
        }];
        
    }
    return _cTextView;
}

- (NSMutableArray *)commentsImages{
    if (!_commentsImages) {
        _commentsImages=[[NSMutableArray alloc]init];
    }
    return _commentsImages;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
